package com.codingfly.service.impl;

import com.codingfly.core.jdbc.service.impl.JPAServiceImpl;
import com.codingfly.entity.SysDictItem;
import com.codingfly.repository.SysDictItemRepository;
import com.codingfly.service.SysDictItemService;
import com.github.wenhao.jpa.Specifications;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class SysDictItemServiceImpl extends JPAServiceImpl<SysDictItemRepository, SysDictItem, Long> implements SysDictItemService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private NamedParameterJdbcTemplate namedJdbcTemplate;
    @Autowired
    private SysDictItemRepository sysDictItemRepository;

    @Override
    public boolean checkHasDictItem(Long dictId) {
        String sql = "SELECT id FROM sys_dict_item WHERE dict_id=? LIMIT 1";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, dictId);
        return !ObjectUtils.isEmpty(list);
    }

    @Override
    public boolean hasChildren(Long id) {
        String sql = "SELECT id FROM sys_dict_item WHERE parent_id=? LIMIT 1";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, id);
        return !ObjectUtils.isEmpty(list);
    }

    @Override
    public SysDictItem findByCode(String code) {
        Optional<SysDictItem> optional = sysDictItemRepository.findOne(Specifications.<SysDictItem>and().eq("code", code).build());
        return optional.isPresent()? optional.get():null;
    }

    @Override
    public List<SysDictItem> children(Long id) {
        Specification specification = Specifications.and().eq("parentId", id).build();
        return sysDictItemRepository.findAll(specification, Sort.by(Sort.Direction.ASC, "orderNo"));
    }

}
